package com.real.operationalcontrols.任务;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.blankj.utilcode.util.ToastUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.real.operationalcontrols.R;
import com.real.operationalcontrols.基类.BaseActivity;
import com.real.operationalcontrols.实体类.LocationBean;
import com.real.operationalcontrols.工具包.NumberUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MapActivity extends BaseActivity implements RouteSearch.OnRouteSearchListener {

    @BindView(R.id.bar_back_btn)
    ImageView barBackBtn;
    @BindView(R.id.bar_title)
    TextView barTitle;
    @BindView(R.id.bar_check_btn)
    TextView barCheckBtn;
    @BindView(R.id.map)
    TextureMapView map;
    @BindView(R.id.chuli_btn)
    TextView chuliBtn;
    @BindView(R.id.daohang_btn)
    TextView daohangBtn;
    AMap aMap = null;
    MyLocationStyle myLocationStyle;
    RouteSearch routeSearch;
    LatLng nowLat;
    double lon, lat;
    boolean isLocationSuccess = true;
    String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_map);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_map;
    }

    @Override
    protected void getData() {
        id = getIntent().getStringExtra("id");
        barTitle.setText("任务地图");
        if (aMap == null) {
            aMap = map.getMap();
        }
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER);
        // 连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

        //获取当前位置
        LiveEventBus.get("location", LocationBean.class).observe(this,
                new Observer<LocationBean>() {
                    @Override
                    public void onChanged(@Nullable LocationBean locationBean) {
                        if (locationBean.getCode() == 200 && isLocationSuccess) {
                            ToastUtils.showShort("定位成功");
                            isLocationSuccess = false;
                            lon = locationBean.getLon();
                            lat = locationBean.getLat();
                            initSearch();
                        }

                        if (locationBean.getCode() != 200) {
                            ToastUtils.showShort("定位中");
                        }
                    }
                });
    }

    private void initSearch() {
        nowLat = new LatLng(lat, lon);
        //获取线路规划
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);
        //设置目的开始标点
        LatLonPoint startPoint = new LatLonPoint(lat, lon);
        //设置目的地坐标点
        LatLonPoint endPoint = new LatLonPoint(38.033629, 115.044185);
        //查询信息对象
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);
        //设置搜索参数 1.fromAndTo 路径的起点终点  2.路径规划的策略(这里是驾车模式,具体看高德API) 3.途
        //经点，可选 4.避让区域，可选， 5.避让道路 ,可选
        RouteSearch.DriveRouteQuery query = new
                RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_SINGLE_DEFAULT, null,
                null, "");
        //开始异步查询
        routeSearch.calculateDriveRouteAsyn(query);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        map.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        map.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }

    @OnClick({R.id.bar_back_btn, R.id.chuli_btn, R.id.daohang_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bar_back_btn:
                finish();
                break;
            case R.id.chuli_btn:
                Intent intent = new Intent(this, TaskMainActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
                break;
            case R.id.daohang_btn:
                NumberUtils.toGaodeDaohang(new LatLng(38.033629, 115.044185), "晋州职教中心", this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int rCode) {
        if (rCode == 1000) {//获取规划路线成功,获取到的是了,路线坐标点的集合

            List<DrivePath> paths = driveRouteResult.getPaths();

            //创建存储坐标点的集合
            List<LatLng> latLngs = new ArrayList<>();

            //遍历获取规划的所有路线坐标点
            for (DrivePath mDrivePath : paths) {
                for (DriveStep mDriveStep : mDrivePath.getSteps()) {
                    for (LatLonPoint mLatLonPoint : mDriveStep.getPolyline()) {
                        latLngs.add(new
                                LatLng(mLatLonPoint.getLatitude(), mLatLonPoint.getLongitude()));
                    }
                }
            }

            //先清除一下,避免重复显示
            aMap.clear();

            //绘制起始位置和目的地marker
            aMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_start))
                    .position(nowLat));
            aMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_end))
                    .position(new LatLng(38.033629, 115.044185)));

            //绘制规划路径路线
            aMap.addPolyline(new PolylineOptions()
                    //路线坐标点的集合
                    .addAll(latLngs)
                    .visible(true)
                    .useGradient(true)
                    //线的宽度
                    .width(30)
                    .color(getResources().getColor(R.color.colorTitle)));//设置画线的颜色

            //显示完整包含所有marker地图路线
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (int i = 0; i < latLngs.size(); i++) {
                builder.include(latLngs.get(i));
            }
            //显示全部marker,第二个参数是四周留空宽度
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 200));
        } else {
            ToastUtils.showShort("线路规划失败");
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }
}
